# -*- coding: utf-8 -*-

from common import *
from glahf import glahf, faceutil
from PyQt4 import QtCore, QtGui
import analyse
import configdialog
import json
import lookdb
import threading
import time
import util

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class MainWindow(QtGui.QWidget):
    '''
    界面主窗口
    '''
    slideSig = QtCore.pyqtSignal(str)

    def __init__(self
                ,parent=None):
        super(MainWindow,self).__init__(parent)
        self.slideSig.connect(self.setImg)
        self.linesArr = None
        self.FSCALE = None
        self.LSCALE = None
        self.RSCALE = None
        self.FRAONTAL_PATH = None
        self.LEFT_PATH = None
        self.RIGHT_PATH = None

        self.LEFT_IR_PATH = None
        self.FRONTAL_IR_PATH = None
        self.RIGHT_IR_PATH = None
        self.config = util.load_config()
        self.scale = None

    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        GLOBAL_HEIGHT, GLOBAL_WIDTH = util.screen_size()
        self.resize(GLOBAL_WIDTH, GLOBAL_HEIGHT)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Microsoft YaHei"))

        self.movie = QtGui.QMovie(LOADING_GIF, QtCore.QByteArray(), self)
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie.setSpeed(100)
        self.dbdialog = lookdb.Ui_Table()
        self.settingsdialog = configdialog.Ui_Dialog()

        png = QtGui.QPixmap(self)
        png.load(BG_IMG)
        palette = QtGui.QPalette(self)
        palette.setBrush(self.backgroundRole(), QtGui.QBrush(png))
        MainWindow.setPalette(palette);
        MainWindow.setAutoFillBackground(True)

        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        font.setPointSize(12)

        self.rightBGLabel = QtGui.QLabel(self.centralwidget)
        self.rightBGLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.76,0,GLOBAL_WIDTH*0.3, GLOBAL_HEIGHT))
        self.rightBGLabel.setStyleSheet("QLabel{background:rgb(13, 25, 38)}")

        # 灰度值分析按钮
        self.analyseButton = QtGui.QPushButton(self.centralwidget)
        self.analyseButton.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.76, GLOBAL_HEIGHT*0.10, GLOBAL_WIDTH*0.27, GLOBAL_HEIGHT*0.17))
        self.analyseButton.setObjectName(_fromUtf8("analyseButton"))
        self.analyseButton.setFont(font)
        # 数据库按钮
        self.dbButton = QtGui.QPushButton(self.centralwidget)
        self.dbButton.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.76, GLOBAL_HEIGHT*0.30, GLOBAL_WIDTH*0.27, GLOBAL_HEIGHT*0.17))
        self.dbButton.setObjectName(_fromUtf8("dbButton"))
        self.dbButton.setFont(font)
        # 设置按钮
        self.settingButton = QtGui.QPushButton(self.centralwidget)
        self.settingButton.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.76, GLOBAL_HEIGHT*0.50, GLOBAL_WIDTH*0.27, GLOBAL_HEIGHT*0.17))
        self.settingButton.setObjectName(_fromUtf8("settingButton"))
        self.settingButton.setFont(font)
        # 退出按钮
        self.exitButton = QtGui.QPushButton(self.centralwidget)
        self.exitButton.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.76, GLOBAL_HEIGHT*0.70, GLOBAL_WIDTH*0.27, GLOBAL_HEIGHT*0.17))
        self.exitButton.setObjectName(_fromUtf8("exitButton"))
        self.exitButton.setFont(font)
        
        MainWindow.setCentralWidget(self.centralwidget)

        # 左侧预览
        self.leftLabel = QtGui.QLabel(self.centralwidget)
        self.leftLabel.setScaledContents(True)
        self.leftLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.05, GLOBAL_HEIGHT*0.07, GLOBAL_WIDTH*0.18, GLOBAL_HEIGHT*0.35))
        self.leftLabel.setObjectName(_fromUtf8("leftLabel"))
        # 中间预览
        self.frontalLabel = QtGui.QLabel(self.centralwidget)
        self.frontalLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.3, GLOBAL_HEIGHT*0.07, GLOBAL_WIDTH*0.18, GLOBAL_HEIGHT*0.35))
        self.frontalLabel.setObjectName(_fromUtf8("frontalLabel"))
        self.frontalLabel.setScaledContents(True)
        # 右侧预览
        self.rightLabel = QtGui.QLabel(self.centralwidget)
        self.rightLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.55, GLOBAL_HEIGHT*0.07, GLOBAL_WIDTH*0.18, GLOBAL_HEIGHT*0.35))
        self.rightLabel.setObjectName(_fromUtf8("rightLabel"))
        self.rightLabel.setScaledContents(True)

        # 左侧IR预览
        self.leftIRLabel = QtGui.QLabel(self.centralwidget)
        self.leftIRLabel.setScaledContents(True)
        self.leftIRLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.05, GLOBAL_HEIGHT*0.50, GLOBAL_WIDTH*0.18, GLOBAL_HEIGHT*0.35))
        self.leftIRLabel.setObjectName(_fromUtf8("leftIRLabel"))
        # 中间IR预览
        self.frontalIRLabel = QtGui.QLabel(self.centralwidget)
        self.frontalIRLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.3, GLOBAL_HEIGHT*0.50, GLOBAL_WIDTH*0.18, GLOBAL_HEIGHT*0.35))
        self.frontalIRLabel.setObjectName(_fromUtf8("frontalIRLabel"))
        self.frontalIRLabel.setScaledContents(True)
        # 右侧IR预览
        self.rightIRLabel = QtGui.QLabel(self.centralwidget)
        self.rightIRLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.55, GLOBAL_HEIGHT*0.50, GLOBAL_WIDTH*0.18, GLOBAL_HEIGHT*0.35))
        self.rightIRLabel.setObjectName(_fromUtf8("rightLIRabel"))
        self.rightIRLabel.setScaledContents(True)

        # 选择左脸
        self.chooseLeftFace = QtGui.QPushButton(self.centralwidget)
        self.chooseLeftFace.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.06, GLOBAL_HEIGHT*0.43, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.1))
        self.chooseLeftFace.setObjectName(_fromUtf8("chooseLeftFace"))
        self.chooseLeftIRFace = QtGui.QPushButton(self.centralwidget)
        self.chooseLeftIRFace.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.14, GLOBAL_HEIGHT*0.43, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.1))
        self.chooseLeftIRFace.setObjectName(_fromUtf8("chooseLeftIRFace"))
        # 选择正脸
        self.chooseFrontalFace = QtGui.QPushButton(self.centralwidget)
        self.chooseFrontalFace.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.31, GLOBAL_HEIGHT*0.43, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.1))
        self.chooseFrontalFace.setObjectName(_fromUtf8("chooseFrontalFace"))
        self.chooseFrontalIRFace = QtGui.QPushButton(self.centralwidget)
        self.chooseFrontalIRFace.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.39, GLOBAL_HEIGHT*0.43, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.1))
        self.chooseFrontalIRFace.setObjectName(_fromUtf8("chooseFrontalIRFace"))
        # 选择右脸
        self.chooseRightFace = QtGui.QPushButton(self.centralwidget)
        self.chooseRightFace.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.56, GLOBAL_HEIGHT*0.43, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.1))
        self.chooseRightFace.setObjectName(_fromUtf8("chooseRightFace"))
        self.chooseRightIRFace = QtGui.QPushButton(self.centralwidget)
        self.chooseRightIRFace.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.64, GLOBAL_HEIGHT*0.43, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.1))
        self.chooseRightIRFace.setObjectName(_fromUtf8("chooseRightIRFace"))

        # 左缩放
        self.leftScale = QtGui.QSlider(MainWindow)
        self.leftScale.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.08, GLOBAL_HEIGHT*0.89, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.05))
        self.leftScale.setOrientation(QtCore.Qt.Horizontal)
        self.leftScale.setObjectName(_fromUtf8("leftScale"))
        self.leftScale.setRange(0, 3)
        self.leftScaleLabel = QtGui.QLabel(MainWindow)
        self.leftScaleLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.02, GLOBAL_HEIGHT*0.90, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.02))
        self.leftScaleLabel.setObjectName(_fromUtf8("leftScaleLabel"))
        self.leftlcdNum = QtGui.QLCDNumber(MainWindow)
        self.leftlcdNum.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.19, GLOBAL_HEIGHT*0.895, GLOBAL_WIDTH*0.05, 23))
        self.leftlcdNum.setObjectName(_fromUtf8("leftlcdNum"))
        # 右缩放
        self.rightScale = QtGui.QSlider(MainWindow)
        self.rightScale.setRange(0, 3)
        self.rightScale.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.59, GLOBAL_HEIGHT*0.89, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.05))
        self.rightScale.setOrientation(QtCore.Qt.Horizontal)
        self.rightScale.setObjectName(_fromUtf8("rightScale"))
        self.rightScaleLabel = QtGui.QLabel(MainWindow)
        self.rightScaleLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.53, GLOBAL_HEIGHT*0.90, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.02))
        self.rightScaleLabel.setObjectName(_fromUtf8("rightScaleLabel"))
        self.rightlcdNum = QtGui.QLCDNumber(MainWindow)
        self.rightlcdNum.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.70, GLOBAL_HEIGHT*0.895, GLOBAL_WIDTH*0.05, 23))
        self.rightlcdNum.setObjectName(_fromUtf8("rightlcdNum"))
        # 中缩放
        self.frontalScale = QtGui.QSlider(MainWindow)
        self.frontalScale.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.34, GLOBAL_HEIGHT*0.89, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.05))
        self.frontalScale.setOrientation(QtCore.Qt.Horizontal)
        self.frontalScale.setObjectName(_fromUtf8("leftScale"))
        self.frontalScale.setRange(0, 3)
        self.frontalScaleLabel = QtGui.QLabel(MainWindow)
        self.frontalScaleLabel.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.28, GLOBAL_HEIGHT*0.90, GLOBAL_WIDTH*0.1, GLOBAL_HEIGHT*0.02))
        self.frontalScaleLabel.setObjectName(_fromUtf8("rightScaleLabel"))
        self.frontallcdNum = QtGui.QLCDNumber(MainWindow)
        self.frontallcdNum.setGeometry(QtCore.QRect(GLOBAL_WIDTH*0.45, GLOBAL_HEIGHT*0.895, GLOBAL_WIDTH*0.05, 23))
        self.frontallcdNum.setObjectName(_fromUtf8("rightlcdNum"))
        # 字体
        font.setPointSize(9)
        self.frontalScaleLabel.setFont(font)
        self.leftScaleLabel.setFont(font)
        self.rightScaleLabel.setFont(font)
        self.chooseLeftFace.setFont(font)
        self.chooseFrontalFace.setFont(font)
        self.chooseRightFace.setFont(font)
        self.chooseLeftIRFace.setFont(font)
        self.chooseFrontalIRFace.setFont(font)
        self.chooseRightIRFace.setFont(font)

        # 初始化滑条
        self.leftlcdNum.display(1.0)
        self.frontallcdNum.display(1.0)
        self.rightlcdNum.display(1.0)

        self.connect(self.frontalScale, QtCore.SIGNAL("valueChanged(int)"),lambda :self.slider_change("frontal"))
        self.connect(self.leftScale, QtCore.SIGNAL("valueChanged(int)"),lambda :self.slider_change("left"))
        self.connect(self.rightScale, QtCore.SIGNAL("valueChanged(int)"),lambda :self.slider_change("right"))
        self.connect(self.chooseLeftFace,QtCore.SIGNAL('clicked()'),lambda :self.get_face("left","normal"))
        self.connect(self.chooseFrontalFace,QtCore.SIGNAL('clicked()'),lambda :self.get_face("frontal","normal"))
        self.connect(self.chooseRightFace,QtCore.SIGNAL('clicked()'),lambda :self.get_face("right","normal"))

        self.connect(self.chooseLeftIRFace,QtCore.SIGNAL('clicked()'),lambda :self.get_face("left","ir"))
        self.connect(self.chooseFrontalIRFace,QtCore.SIGNAL('clicked()'),lambda :self.get_face("frontal","ir"))
        self.connect(self.chooseRightIRFace,QtCore.SIGNAL('clicked()'),lambda :self.get_face("right","ir"))

        self.connect(self.analyseButton,QtCore.SIGNAL('clicked()'),self.beginAnalyse)
        self.connect(self.dbButton,QtCore.SIGNAL('clicked()'),self.dbdialog.show)
        self.connect(self.settingButton,QtCore.SIGNAL('clicked()'),self.settingsdialog.show)
        self.connect(self.exitButton,QtCore.SIGNAL('clicked()'),QtGui.qApp,QtCore.SLOT('quit()'))
        
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "人脸灰度值定位", None))
        # self.analyseButton.setText(_translate("MainWindow", "灰度值分析", None))
        # self.dbButton.setText(_translate("MainWindow", "数据库", None))
        # self.settingButton.setText(_translate("MainWindow", "设置", None))
        # self.exitButton.setText(_translate("MainWindow", "退出", None))
        self.frontalLabel.setText(_translate("MainWindow", "正脸", None))
        self.frontalScaleLabel.setText(_translate("Dialog", "缩放比例", None))

        self.chooseLeftFace.setText(_translate("MainWindow", "选择左脸", None))
        self.chooseFrontalFace.setText(_translate("MainWindow", "选择正脸", None))
        self.chooseRightFace.setText(_translate("MainWindow", "选择右脸", None))
        self.chooseLeftIRFace.setText(_translate("MainWindow", "红外图像", None))
        self.chooseFrontalIRFace.setText(_translate("MainWindow", "红外图像", None))
        self.chooseRightIRFace.setText(_translate("MainWindow", "红外图像", None))

        self.leftScaleLabel.setText(_translate("MainWindow", "左脸缩放比例", None))
        self.rightScaleLabel.setText(_translate("MainWindow", "右脸缩放比例", None))
        self.frontalScaleLabel.setText(_translate("MainWindow", "正脸缩放比例", None))


        btns = [self.chooseLeftFace, 
                self.chooseFrontalFace, 
                self.chooseRightFace
                ]
        ir_btns = [self.chooseLeftIRFace,
                 self.chooseFrontalIRFace,
                 self.chooseRightIRFace
                ]

        pixmap = QtGui.QPixmap(SEARCH_IMG)

        for btn in btns:
            btn.setIcon(QtGui.QIcon(pixmap))
            btn.setIconSize(pixmap.size())
            btn.setFixedSize(100, 35)
            btn.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"\
            "QPushButton:hover{background:rgb(140, 220, 35)}")

        for btn in ir_btns:
            btn.setIcon(QtGui.QIcon(pixmap))
            btn.setIconSize(pixmap.size())
            btn.setFixedSize(100, 35)
            btn.setStyleSheet("QPushButton{border-radius:5px;background:rgb(255, 48, 48);color:white}"\
            "QPushButton:hover{background:rgb(205, 38, 38)}")

        self.leftLabel.setPixmap(QtGui.QPixmap(INIT_LEFTIMG))
        self.frontalLabel.setPixmap(QtGui.QPixmap(INIT_FRONTALIMG))
        self.rightLabel.setPixmap(QtGui.QPixmap(INIT_RIGHTIMG))

        self.leftIRLabel.setPixmap(QtGui.QPixmap(INIT_LEFTIMG))
        self.frontalIRLabel.setPixmap(QtGui.QPixmap(INIT_FRONTALIMG))
        self.rightIRLabel.setPixmap(QtGui.QPixmap(INIT_RIGHTIMG))


        # for btn in [self.analyseButton,self.dbButton,
        #                     self.settingButton,self.exitButton]:
        #     shadow = QtGui.QGraphicsDropShadowEffect(self)
        #     shadow.setBlurRadius(15)
        #     shadow.setOffset(2,2)
        #     btn.setGraphicsEffect(shadow)

        self.analyseButton.setStyleSheet(\
            "QPushButton{border-image:url('sys/img/analyse_dark.png')}"\
            "QPushButton:hover{border-image:url('sys/img/analyse_light.png')}")
        self.dbButton.setStyleSheet(\
            "QPushButton{border-image:url('sys/img/db_dark.png')}"\
            "QPushButton:hover{border-image:url('sys/img/db_light.png')}")
        self.settingButton.setStyleSheet(\
            "QPushButton{border-image:url('sys/img/setting_dark.png')}"\
            "QPushButton:hover{border-image:url('sys/img/setting_light.png')}")
        self.exitButton.setStyleSheet(\
            "QPushButton{border-image:url('sys/img/exit_dark.png')}"\
            "QPushButton:hover{border-image:url('sys/img/exit_light.png')}")

    def loading(self):
        '''
        加载载入动画。
        '''
        self.frontalLabel.setMovie(self.movie)
        self.movie.start()

    def get_face(self, part, mode):
        # 左脸,正脸,右脸
        assert part in ("left","frontal","right")
        # 正常模式, 红外模式
        assert mode in ("normal","ir")

        PATH = unicode(self.showFileDialog())

        if PATH:
            if part == "left":
                if mode == "normal":
                    self.LEFT_PATH = PATH.encode('gbk')
                    IMG = glahf.read(self.LEFT_PATH)
                    glahf.write(LEFT_ORIG_PATH,IMG)
                    glahf.write(LEFT_TEMP_PATH,IMG)
                    self.leftLabel.setPixmap(QtGui.QPixmap(r''+LEFT_ORIG_PATH))
                    self.slider_change("left")
                else:
                    self.LEFT_IR_PATH = PATH.encode('gbk')
                    self.slider_change("left")

            elif part == "frontal":
                if mode == "normal":
                    self.FRAONTAL_PATH = PATH.encode('gbk')
                    FRONTAL = glahf.read(self.FRAONTAL_PATH)
                    if self.config['lockeyes']:
                        IMG, self.scale = glahf.adjustface(FRONTAL, zoom_factor=0.4)
                    else:
                        IMG = FRONTAL
                    self.linesArr,status = glahf.markdetect(IMG)
                    if status == False:
                        m = util.get_memory()
                        if m is not None and isinstance(m,list):
                            self.linesArr = m
                    print "detect status:",status
                    glahf.write(FACE_ORIG_PATH, FRONTAL)
                    glahf.write(FACE_TEMP_PATH, IMG)
                    if self.FSCALE is not None and self.FSCALE >0:
                        self.slider_change("frontal")
                    else:
                        self.frontalLabel.setPixmap(QtGui.QPixmap(r''+FACE_TEMP_PATH))
                else:
                    self.FRONTAL_IR_PATH = PATH.encode('gbk')
                    self.slider_change("frontal")

            elif part == "right":
                if mode == "normal":
                    self.RIGHT_PATH = PATH.encode('gbk')
                    IMG = glahf.read(self.RIGHT_PATH)
                    glahf.write(RIGHT_ORIG_PATH,IMG)
                    glahf.write(RIGHT_TEMP_PATH,IMG)
                    self.rightLabel.setPixmap(QtGui.QPixmap(r''+RIGHT_ORIG_PATH))
                    self.rightSliderChange()
                else:
                    self.RIGHT_IR_PATH = PATH.encode('gbk')
                    self.slider_change("right")
            else:
                raise RuntimeError()

    def slider_change(self, part):
        assert part in("left","frontal","right")
        value = None

        if part == "left":
            value = self.leftScale.value()
            value = float(value)/10
            self.LSCALE = value/2
            self.leftlcdNum.display(value+1)
            if self.LEFT_PATH:
                LEFT_ORIG = glahf.read(self.LEFT_PATH)
                glahf.write(LEFT_TEMP_PATH, glahf.enlargeimage(LEFT_ORIG, self.LSCALE))
                self.leftLabel.setPixmap(QtGui.QPixmap(r''+LEFT_TEMP_PATH))

            if self.LEFT_IR_PATH:
                LEFT_IR_ORIG = glahf.read(self.LEFT_IR_PATH)
                glahf.write(LEFT_TEMP_IR_PATH, glahf.enlargeimage(LEFT_IR_ORIG, self.LSCALE))
                self.leftIRLabel.setPixmap(QtGui.QPixmap(r''+LEFT_TEMP_IR_PATH))

        elif part == "frontal":
            FACE_ORIG = FACE_IR_ORIG = None
            temp = temp_ir = None
            value = self.frontalScale.value()
            value = float(value)/10
            self.FSCALE = value/2
            self.frontallcdNum.display(value+1)

            if self.FRAONTAL_PATH:
                FACE_ORIG = glahf.read(self.FRAONTAL_PATH)
                temp = glahf.enlargeimage(FACE_ORIG, self.FSCALE)
                if self.scale:
                    temp = glahf.enlargeimage(temp, self.scale)
                glahf.write(FACE_TEMP_PATH, temp)
                self.frontalLabel.setPixmap(QtGui.QPixmap(r''+FACE_TEMP_PATH))
            
            if self.FRONTAL_IR_PATH:
                FACE_IR_ORIG = glahf.read(self.FRONTAL_IR_PATH)
                temp_ir = glahf.enlargeimage(FACE_IR_ORIG, self.FSCALE)
                if self.scale:
                    temp_ir = glahf.enlargeimage(temp_ir, self.scale)
                glahf.write(FACE_TEMP_IR_PATH, temp_ir)
                self.frontalIRLabel.setPixmap(QtGui.QPixmap(r''+FACE_TEMP_IR_PATH))

            self.linesArr, status = glahf.markdetect(temp)
            
        elif part == "right":
            value = self.rightScale.value()
            value = float(value)/10
            self.RSCALE = value/2
            self.rightlcdNum.display(value+1)
            if self.RIGHT_PATH:
                RIGHT_ORIG = glahf.read(self.RIGHT_PATH)
                glahf.write(RIGHT_TEMP_PATH, glahf.enlargeimage(RIGHT_ORIG, self.RSCALE))
                self.rightLabel.setPixmap(QtGui.QPixmap(RIGHT_TEMP_PATH))

            if self.RIGHT_IR_PATH:
                RIGHT_IR_ORIG = glahf.read(self.RIGHT_IR_PATH)
                glahf.write(RIGHT_TEMP_IR_PATH, glahf.enlargeimage(RIGHT_IR_ORIG, self.RSCALE))
                self.rightIRLabel.setPixmap(QtGui.QPixmap(r''+RIGHT_TEMP_IR_PATH))
        else:
            raise RuntimeError()

    def setImg(self, path):
        self.frontalLabel.setPixmap(QtGui.QPixmap(path))

    def showFileDialog(self):
        '''
        显示上传文件的对话框。
        '''
        filename = QtGui.QFileDialog.getOpenFileName(self,u'打开图片','./')
        if len(filename) != 0:
            return filename
        return ""

    def beginAnalyse(self):
        '''
        对图片进行灰度值分析，并写入pickle数据库。
        '''
        if not self.LEFT_PATH or not self.RIGHT_PATH or not self.FRAONTAL_PATH:
            util.warn_dialog(self,window="MainWindow",title="消息", text="请选择图片")
            return

        d = faceutil.handle_images(FACE_TEMP_PATH,
                                LEFT_TEMP_PATH,
                                RIGHT_TEMP_PATH,
                                f_ir_face=FACE_TEMP_IR_PATH,
                                l_ir_face=LEFT_TEMP_IR_PATH,
                                r_ir_face=RIGHT_TEMP_IR_PATH,
                                path=self.config['savedir']
                                )

        if not d:
            util.warn_dialog(self,window="MainWindow",title="消息", text="图片处理失败,请检查图片路径是否正确")
            return

        # ORIG
        l_img = glahf.read(LEFT_TEMP_PATH)
        f_img = glahf.read(FACE_TEMP_PATH)
        r_img = glahf.read(RIGHT_TEMP_PATH)

        l_skin, l_skinMask = faceutil.skin(l_img, mode='l')
        f_skin, f_skinMask = faceutil.skin(f_img, mode='f')
        r_skin, r_skinMask = faceutil.skin(r_img, mode='r')

        l_gv = glahf.gray_value_filter(l_skin, 30, 220)
        f_gv = glahf.gray_value_filter(f_skin, 30, 220)
        r_gv = glahf.gray_value_filter(r_skin, 30, 220)
        
        # IR
        l_ir_img = glahf.read(LEFT_TEMP_IR_PATH)
        f_ir_img = glahf.read(FACE_TEMP_IR_PATH)
        r_ir_img = glahf.read(RIGHT_TEMP_IR_PATH)

        l_ir_skin = faceutil.skin(l_ir_img, mode='l', skinMask=l_skinMask)
        f_ir_skin = faceutil.skin(f_ir_img, mode='f', skinMask=f_skinMask)
        r_ir_skin = faceutil.skin(r_ir_img, mode='r', skinMask=r_skinMask)

        l_ir_gv = glahf.gray_value_filter(l_ir_skin, 30, 220)
        f_ir_gv = glahf.gray_value_filter(f_ir_skin, 30, 220)
        r_ir_gv = glahf.gray_value_filter(r_ir_skin, 30, 220)

        clb_gv = 0
        if self.config['calibration'] is True:
            spliced_img = f_img
            clb = util.clb_array()
            if clb:
                height, width = spliced_img.shape[:2]
                s_x = clb['start_x'] * width
                e_x = clb['end_x'] * width
                s_y = clb['start_y'] * height
                e_y = clb['end_y'] * height
                clb_area = spliced_img[s_y:e_y, s_x:e_x]
                # glahf.show(clb_area)
                clb_gv = 255 - glahf.gray_value(clb_area)
                if clb_gv < 0:
                    clb_gv = 0
                l_gv += clb_gv
                f_gv += clb_gv
                r_gv += clb_gv
                l_ir_gv += clb_gv
                f_ir_gv += clb_gv
                r_ir_gv += clb_gv
        d['datas']['l_gv'] =  l_gv
        d['datas']['f_gv'] =  f_gv
        d['datas']['r_gv'] =  r_gv
        d['datas']['l_ir_gv'] =  l_ir_gv
        d['datas']['f_ir_gv'] =  f_ir_gv
        d['datas']['r_ir_gv'] =  r_ir_gv
        d['datas']['clb_gv'] = clb_gv
        d['linesArr'] = self.linesArr
        util.insert_to_db(d)
        id = int(d.get('id'))-1
        self.dbdialog.insertRow(id)
        self.dbdialog.setRowData(id, d)

        self.analysewindow = analyse.AnalyseWindow(linesArr=self.linesArr)
        self.analysewindow.setPath(self.LEFT_PATH, self.FRAONTAL_PATH, self.RIGHT_PATH)
        self.analysewindow.set_avg_gv(l_gv, f_gv, r_gv)
        self.analysewindow.set_avg_ir_gv(l_ir_gv, f_ir_gv, r_ir_gv)
        self.analysewindow.show()
        self.analysewindow.setPreview(d)

